import { message } from 'antd';
import {
  getAllRecords,
  getOneRecords,
  getRecordByVehicleId,
  deleteRecord,
  addRecord,
  updateRecord,
} from './service';
export default {
  namespace: 'accidents',
  state: {
    accidentlist: [],
  },
  reducers: {
    update(state, { payload }) {
      return {
        ...state,
        accidentlist: Array.from(payload),
      };
    },
  },
  effects: {
    *getAllRecords({ payload }, { call, put }) {
      const response = yield call(getAllRecords, payload);
      if (response.code === 0) {
        console.log(response);
        yield put({
          type: 'update',
          payload: response.data,
        });
      } else {
        message.error(response.msg);
      }
    },
    *getOneRecords({ payload }, { call, put }) {
      const response = yield call(getOneRecords, payload);
      if (response.code === 0) {
        const res = [response.data];
        yield put({
          type: 'update',
          payload: res,
        });
      } else {
        message.error(response.msg);
      }
    },
    *getRecordByVehicleId({ payload }, { call, put }) {
      const response = yield call(getRecordByVehicleId, payload);
      if (response.code === 0) {
        console.log(response);
        yield put({
          type: 'update',
          payload: response.data,
        });
      } else {
        message.error(response.msg);
      }
    },
    *deleteRecord({ payload }, { call, put }) {
      const response = yield call(deleteRecord, payload);
      if (response.code === 0) {
        const response = yield call(getAllRecords, payload);
        if (response.code === 0) {
          console.log(response);
          yield put({
            type: 'update',
            payload: response.data,
          });
        } else {
          message.error(response.msg);
        }
      } else {
        message.error(response.msg);
      }
    },
    *addRecord({ payload }, { call, put }) {
      const response = yield call(addRecord, payload);
      if (response.code === 0) {
        const response = yield call(getAllRecords, payload);
        if (response.code === 0) {
          console.log(response);
          yield put({
            type: 'update',
            payload: response.data,
          });
        } else {
          message.error(response.msg);
        }
      } else {
        message.error(response.msg);
      }
    },
    *updateRecord({ payload }, { call, put }) {
      const response = yield call(updateRecord, payload);
      if (response.code === 0) {
        const response = yield call(getAllRecords, payload);
        if (response.code === 0) {
          console.log(response);
          yield put({
            type: 'update',
            payload: response.data,
          });
        } else {
          message.error(response.msg);
        }
      } else {
        message.error(response.msg);
      }
    },
  },
};
